﻿using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Xoohoo.Extensions;
using Xoohoo.Models;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Repositories.SqlServerEntLibDAB
{
    public class BulletinRepository : RepositoryBase,IBulletinRepository
    {
        private readonly Database _db;

        public BulletinRepository(string connectionStringName)
        {
            this._db = DatabaseFactory.CreateDatabase(connectionStringName);
        }

        public Bulletin GetItem()
        {
            string sql = "select top 1 * from Bulletin";
            DbCommand cmd = _db.GetSqlStringCommand(sql);
            IDataReader dr = _db.ExecuteReader(cmd);
            return Project(dr);
        }

        public bool Save(BulletinInput bulletin)
        {
            string sql = @"Update Bulletin Set
                            Title=@Title
                            ,Content=@Content
                            ,PublishDate=@PublishDate
                            ,IsShow=@IsShow";
        

            DbCommand cmd = _db.GetSqlStringCommand(sql);
            _db.AddInParameter(cmd, "Title", DbType.String, bulletin.Title);
            _db.AddInParameter(cmd, "Content", DbType.String, bulletin.Content);
            _db.AddInParameter(cmd, "PublishDate", DbType.DateTime, bulletin.PublishDate);
            _db.AddInParameter(cmd, "IsShow", DbType.Boolean, bulletin.IsShow);

            _db.ExecuteNonQuery(cmd);

            return true;
        }

        #region Private Methods

        private Bulletin Project(IDataReader dr)
        {
            Bulletin item = null;
            if (dr.Read())
            {
                item = dr.ToModel<Bulletin>();
            }
            dr.Close();
            return item;
        }

        #endregion

    }
}
